package qlsl.androiddesign.api.view.commonview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.PointF;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * 双层嵌套子ViewPager<br/>
 * 
 */
public class ChildViewPager extends ViewPager {

	private PointF downP = new PointF();

	private PointF curP = new PointF();

	private OnSingleTouchListener onSingleTouchListener;

	private boolean intercept = false;

	public ChildViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public ChildViewPager(Context context) {
		super(context);
	}

	public boolean onInterceptTouchEvent(MotionEvent arg0) {
		if (!intercept) {
			return super.onInterceptTouchEvent(arg0);
		}
		return intercept;
	}

	@SuppressLint("ClickableViewAccessibility")
	public boolean onTouchEvent(MotionEvent arg0) {
		if (intercept) {
			curP.x = arg0.getX();
			curP.y = arg0.getY();
			if (arg0.getAction() == MotionEvent.ACTION_DOWN) {
				downP.x = arg0.getX();
				downP.y = arg0.getY();
				getParent().requestDisallowInterceptTouchEvent(true);
			}
			if (arg0.getAction() == MotionEvent.ACTION_MOVE) {
				getParent().requestDisallowInterceptTouchEvent(true);
			}
			if (arg0.getAction() == MotionEvent.ACTION_UP) {
				if (downP.x == curP.x && downP.y == curP.y) {
					onSingleTouch();
					return true;
				}
			}
		}
		return super.onTouchEvent(arg0);
	}

	public void onSingleTouch() {
		if (onSingleTouchListener != null) {
			onSingleTouchListener.onSingleTouch();
		}
	}

	public void setIntercept(boolean intercept) {
		this.intercept = intercept;
	}

	public interface OnSingleTouchListener {
		public void onSingleTouch();
	}

	public void setOnSingleTouchListener(
			OnSingleTouchListener onSingleTouchListener) {
		this.onSingleTouchListener = onSingleTouchListener;
	}
}